package broadcast;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import scala.Int;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BroadCast {
    public static void main(String[] args) throws Exception {
    //    DataSet计算，创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    //    创建broadcast的数据
        ArrayList<Tuple2<String,Integer>> people = new  ArrayList<Tuple2<String, Integer>>();
        people.add(new Tuple2<String, Integer>("bing",12));
        people.add(new Tuple2<String, Integer>("shui",13));
        people.add(new Tuple2<String, Integer>("dabing",14));
        DataSet<Tuple2<String, Integer>> peopledata = env.fromCollection(people);

    //    创建broadcast
        final DataSet<HashMap<String, Integer>> broadcast = peopledata.map(new MapFunction<Tuple2<String, Integer>, HashMap<String, Integer>>() {
            public HashMap<String, Integer> map(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                HashMap<String, Integer> result = new HashMap<String, Integer>();
                result.put(stringIntegerTuple2.f0, stringIntegerTuple2.f1);
                return result;
            }
        });

    //    定义一个计算
        DataSource<String> source = env.fromElements("bing", "shui", "dabing","meiyou");
        DataSet<String> final_result = source.map(new RichMapFunction<String, String>() {

            // 定义变量保存结果
            HashMap<String, Integer> allpeople = new HashMap<String, Integer>();

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                List<HashMap<String, Integer>> broadcastdata = this.getRuntimeContext().getBroadcastVariable("peoplebroadcast");
                for (HashMap<String, Integer> i : broadcastdata) {
                    System.out.println(i);
                    allpeople.putAll(i);
                }
                System.out.println(allpeople);
            }

            @Override
            public String map(String s) throws Exception {
                Integer age = allpeople.get(s);
                return "name:" + s + " | age:" + age;
            }

        }).withBroadcastSet(broadcast, "peoplebroadcast");

        final_result.print();

    }
}
